package com.ftg.learn.ai;

import com.alibaba.dashscope.aigc.completion.ChatCompletion;
import com.alibaba.dashscope.aigc.completion.ChatCompletionChunk;
import com.alibaba.dashscope.aigc.completion.ChatCompletionParam;
import com.alibaba.dashscope.aigc.completion.ChatCompletions;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import io.reactivex.Flowable;

import java.util.Arrays;
import java.util.Collections;

/**
 * @author 布衣
 */
public class TestAi {
    public static void main(String[] args) {

        //给定key
        Constants.apiKey = "sk-44547a4c94fc4ccdb0c99c0dfdbe5f1d";
        Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1";


        //创建核心对话对象
        ChatCompletions c = new ChatCompletions();

        //构建参数
        Message mess1 = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("你是一个专业的动物学家!")
                .build();

        Message mess = Message.builder()
                .role(Role.USER.getValue())
                .content("蛇是什么?")
                .build();

        ChatCompletionParam params = ChatCompletionParam.builder()
                .messages(Arrays.asList(mess1,mess))
                .model("qwen-plus")
                .stream(true)
                .build();

        //调用了
        try {
            // 使用流式调用
            Flowable<ChatCompletionChunk> flowable = c.streamCall(params);

            // 订阅流并处理每个chunk
            flowable.blockingForEach(chunk -> {
                // 获取每个chunk中的内容并打印
                if (chunk.getChoices() != null && !chunk.getChoices().isEmpty()) {
                    ChatCompletionChunk.Choice choice = chunk.getChoices().get(0);
                    if (choice.getDelta() != null && choice.getDelta().getContent() != null) {
                        System.out.print(choice.getDelta().getContent());
                    }
                }
            });
//            ChatCompletion call = c.call(params);
//            call.getChoices().forEach(System.out::println);
//            System.out.println(call.getObject().toString());
        } catch (NoApiKeyException e) {
            throw new RuntimeException(e);
        } catch (InputRequiredException e) {
            throw new RuntimeException(e);
        }
    }
}